import { Controller, Post, Get, Del, Inject, Body, Query, Param } from '@midwayjs/core';
import { DetectionService } from '../service/detection.service';
import { Context } from '@midwayjs/koa';

@Controller('/api/detection/history')
export class DetectionController {
  @Inject()
  detectionService: DetectionService;

  @Inject()
  ctx: Context;

  @Post('/create')
  async create(@Body() body: { imageUrl?: string }) {
    try {
      // 关键功能：从 JWT 解析用户 ID，并校验 imageUrl
      const userId = this.ctx.user?.userId;
      if (!userId) {
        return { code: 401, message: '用户未授权', data: null };
      }
      if (!body?.imageUrl) {
        return { code: 400, message: 'imageUrl 不能为空', data: null };
      }
      const result = await this.detectionService.createHistory(userId, body.imageUrl);
      return result;
    } catch (error) {
      return { code: 400, message: error.message || '创建失败', data: null };
    }
  }

  @Get('/list')
  async list(@Query('page') page = '1', @Query('pageSize') pageSize = '10') {
    try {
      // 关键功能：获取分页参数，并按当前用户返回列表
      const userId = this.ctx.user?.userId;
      if (!userId) {
        return { code: 401, message: '用户未授权', data: null };
      }
      const p = Math.max(parseInt(String(page) || '1', 10), 1);
      const ps = Math.max(parseInt(String(pageSize) || '10', 10), 1);
      const result = await this.detectionService.listHistory(userId, p, ps);
      return result;
    } catch (error) {
      return { code: 400, message: error.message || '获取失败', data: null };
    }
  }

  @Del('/delete/:id')
  async delete(@Param('id') id: string) {
    try {
      // 关键功能：只允许删除当前登录用户的记录
      const userId = this.ctx.user?.userId;
      if (!userId) {
        return { code: 401, message: '用户未授权', data: null };
      }
      const parsedId = parseInt(String(id), 10);
      if (!parsedId || parsedId <= 0) {
        return { code: 400, message: '无效的记录ID', data: null };
      }
      const result = await this.detectionService.deleteHistory(userId, parsedId);
      return result;
    } catch (error) {
      return { code: 400, message: error.message || '删除失败', data: null };
    }
  }
}